let fs = require('fs');
let path = require('path');

let gulp = require('gulp');
let concat = require('gulp-concat');
let rename = require('gulp-rename');
let uglify = require('gulp-uglify');
let sourcemaps = require('gulp-sourcemaps');
let clean = require('gulp-clean');
let merge = require('merge-stream')

//js模块源文件目录
const SRC = './jsModules';
//js模块构建的文件位置
const DEST = './js';

//获取目录中所有的文件夹
function getFolders(dir){
	return fs.readdirSync(dir)
		.filter(function(file){
			return fs.statSync(path.join(dir, file)).isDirectory();
		})
}

//构建任务
gulp.task('build',function() {
	let folders = getFolders(SRC);
	let tasks = folders.map(function(folder) {
		console.log('正在构建' + path.join(DEST, folder))
		return gulp.src(path.join(SRC, folder, '/*.js'))
			.pipe(sourcemaps.init())
//			.pipe(concat(folder + '.js'))
//			.pipe(gulp.dest(DEST))
			.pipe(uglify())
			.pipe(rename(folder + '.min.js'))
			.pipe(sourcemaps.write('.'))
			.pipe(gulp.dest(DEST))
	});
	
	return merge(tasks);
})

//清理任务
gulp.task('clean', function(){
	let folders = getFolders(SRC);
	let tasks = folders.map(function(folder) {
		console.log('正在清理' + path.join(DEST, folder + '*'));
		return gulp.src(path.join(DEST, folder + '*'), {read:false})
			.pipe(clean())
	})
})

//监听文件变动
gulp.task('auto',function(){
	gulp.watch(SRC + '/*/*.js',['clean','build'])
})
gulp.task('cleanBuild',['clean','build']);
gulp.task('default',['clean','build','auto']);